import Vue from 'vue'
import VueRouter from 'vue-router'
import { userInfoApi } from '@/api/loginApi.js'
import store from '@/store'
import { Toast } from 'vant'
import { localGet } from '@/utils/mylocal.js'
// 导入组件
const Login = () => import('../views/login/login.vue')
const Home = () => import('../views/home/home.vue')
const Index = () => import('../views/home/index/index.vue')
const My = () => import('../views/home/my/my.vue')
const Search = () => import('../views/home/search/search.vue')
const SearchResult = () => import('../views/searchResult/searchResult.vue')
const Detail = () => import('../views/detail/detail.vue')
const Info = () => import('../views/info/info.vue')
const Zhi = () => import('../views/zhi/zhi.vue')

Vue.use(VueRouter)

const routes = [
  // 登录路由:登录成功之后，应该跳转到我的页面
  { path: '/login', component: Login },
  // 验证登录路由:登录成功之后，返回到上一个页面
  { path: '/checkLogin', component: Login },
  // 注册 home 路由
  {
    path: '/home',
    component: Home,
    redirect: '/my',
    children: [
      { path: '/index', component: Index }, // 主页路由
      { path: '/my', component: My, meta: { needLogin: true } }, // 我的路由
      { path: '/search', component: Search }, // 搜索路由,
      { path: '/video', component: () => import('@/views/home/video') } // 搜索路由
    ]
  },
  { path: '/searchResult/:key', component: SearchResult },
  // 文章详情
  { path: '/detail/:artid', component: Detail },
  { path: '/info', component: Info, meta: { needLogin: true } },
  // 小智同学
  { path: '/zhi', component: Zhi }
]

const router = new VueRouter({
  routes
})
router.beforeEach(async (to, from, next) => {
  from.meta.scrollTop =
    document.documentElement.scrollTop ||
    window.pageYOffset ||
    document.body.scrollTop
  if (to.meta.needLogin) {
    // 如果页面需要登录，且needLogin却为true
    if (localGet('token')) {
      // 获取用户信息并渲染
      const res = await userInfoApi()
      store.commit('getUserInfo', res.data)
      next()
    } else {
      // 如果页面需要登录，needLogin却为false
      Toast.fail('对不起，需要登录，请先登录')
      // 将此页面的路由 地址当作参数传递到登录页面的路由中，以确定登录后需要跳转的页面
      router.push('/login?_redirect=' + to.fullPath)
    }
  } else {
    next()
  }
})
export default router
